// Package api 的交易模块：提供交易记录的创建、状态更新、分页查询与统计接口。
package api

import (
	"encoding/json"
	"net/http"
	"strconv"
	"time"

	"github.com/we-pay-kit/we-pay-kit/internal/db"
	"github.com/we-pay-kit/we-pay-kit/internal/repository"
)

type TransactionHandler struct {
	repo *repository.TransactionRepository
}

func NewTransactionHandler() *TransactionHandler {
	return &TransactionHandler{repo: repository.NewTransactionRepository(db.GetDB())}
}

// POST /api/v1/transactions
func (h *TransactionHandler) CreateTransaction(w http.ResponseWriter, r *http.Request) {
	var in struct {
		TransactionID   string  `json:"transaction_id"`
		ActivityID      *int64  `json:"activity_id"`
		PhoneNumber     *string `json:"phone_number"`
		UserID          *string `json:"user_id"`
		OrderAmount     float64 `json:"order_amount"`
		DiscountAmount  float64 `json:"discount_amount"`
		ActualPayAmount float64 `json:"actual_pay_amount"`
		TransactionTime string  `json:"transaction_time"`
		TransactionType string  `json:"transaction_type"`
		Status          string  `json:"status"`
		PaymentChannel  string  `json:"payment_channel"`
		CouponID        *string `json:"coupon_id"`
	}
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	tt, err := time.Parse(time.RFC3339, in.TransactionTime)
	if err != nil {
		http.Error(w, "invalid transaction_time", http.StatusBadRequest)
		return
	}
	t := &repository.TransactionRecord{
		TransactionID:   in.TransactionID,
		ActivityID:      in.ActivityID,
		PhoneNumber:     in.PhoneNumber,
		UserID:          in.UserID,
		OrderAmount:     in.OrderAmount,
		DiscountAmount:  in.DiscountAmount,
		ActualPayAmount: in.ActualPayAmount,
		TransactionTime: tt,
		TransactionType: in.TransactionType,
		Status:          in.Status,
		PaymentChannel:  in.PaymentChannel,
		CouponID:        in.CouponID,
	}
	id, err := h.repo.Create(r.Context(), t)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(map[string]any{"id": id})
}

// PATCH /api/v1/transactions/status?transaction_id=xxx&status=SUCCESS
func (h *TransactionHandler) UpdateStatus(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	tid := q.Get("transaction_id")
	status := q.Get("status")
	if tid == "" || status == "" {
		http.Error(w, "missing params", http.StatusBadRequest)
		return
	}
	if err := h.repo.UpdateStatus(r.Context(), tid, status); err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.WriteHeader(http.StatusNoContent)
}

// GET /api/v1/transactions?limit=20&offset=0
func (h *TransactionHandler) ListTransactions(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	limit, _ := strconv.Atoi(q.Get("limit"))
	offset, _ := strconv.Atoi(q.Get("offset"))
	list, err := h.repo.List(r.Context(), limit, offset)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(list)
}

// GET /api/v1/transactions/stats?from=2025-09-01T00:00:00Z&to=2025-09-02T00:00:00Z
func (h *TransactionHandler) Stats(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	fromStr := q.Get("from")
	toStr := q.Get("to")
	if fromStr == "" || toStr == "" {
		http.Error(w, "missing from/to", http.StatusBadRequest)
		return
	}
	from, err := time.Parse(time.RFC3339, fromStr)
	if err != nil {
		http.Error(w, "invalid from", http.StatusBadRequest)
		return
	}
	to, err := time.Parse(time.RFC3339, toStr)
	if err != nil {
		http.Error(w, "invalid to", http.StatusBadRequest)
		return
	}
	stats, err := h.repo.StatsByRange(r.Context(), from, to)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(stats)
}
